/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.controller;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * banner
 *
 */
@RestController
@RequestMapping("/api/file")
public class ApiFileController {

    @GetMapping("download")
    @ApiOperation(value = "下载")
    public ResponseEntity<byte[]> testResponseEntity(String fileName, HttpServletRequest request, HttpServletResponse response) {
        ResponseEntity<byte[]> responseEntity = null;
        try {
            // 服务器文件路径
            String serverFilePath = "/root/xiaohai/files/" + fileName;
            File serverFile = new File(serverFilePath);

            // 响应头，告知浏览器下载附件
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + serverFile.getName());
            // 响应内容。
            byte[] body = FileUtil.readBytes(serverFile);
            // 响应状态
            HttpStatus statusCode = HttpStatus.OK;

            responseEntity = new ResponseEntity<>(body, headers, statusCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseEntity;
    }


}